package com.jzr.task.job;

import com.jzr.task.db1.model.TSysJob;
import com.jzr.task.db1.service.TSysJobService;
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;

@Getter
@Setter
public abstract class BaseJob implements Runnable {
    @Autowired
    protected TSysJobService sysJobService;

    protected final Logger log = LoggerFactory.getLogger(this.getClass());
    private Integer jobId;
    private boolean isRun = false;

    @Override
    public void run() {
        isRun = true;
        boolean isSuccess = false;
        try {
            //保存信息
            TSysJob tmpJob = new TSysJob();
            tmpJob.setId(getJobId());
            tmpJob.setIsRun(isRun);
            tmpJob.setStartDate(LocalDateTime.now());
            tmpJob.setHasError(false);
            sysJobService.save(tmpJob);
            process();
            isSuccess = true;
        }catch (Throwable e){
            try{
                sysJobService.addErrLog(jobId,e.getMessage());
            }catch (Throwable ex){}
            e.printStackTrace();
            log.error(e.getMessage());
        }finally {
            isRun = false;
            //保存信息
            TSysJob tmpJob = new TSysJob();
            tmpJob.setId(getJobId());
            tmpJob.setIsRun(isRun);
            tmpJob.setStopDate(LocalDateTime.now());
            if(isSuccess){
                tmpJob.setLastSuccessDate(LocalDateTime.now());
            }
            sysJobService.save(tmpJob);
        }
    }

    public void process() throws Exception {

    }

    protected void addErrLog(String msg){
        try {
            sysJobService.addErrLog(jobId, msg);
        }catch (Throwable e){}
    }

    protected LocalDateTime getLastSuccessDate(){
        return sysJobService.getLastSuccessDate(jobId);
    }

    protected void setLastSuccessDate(){
        sysJobService.setLastSuccessDate(jobId);
    }
}
